package dome1.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketException;

//服务器
public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true) {
            //3、读取请求并解析
            //创建一个数据包，将读取的字节数据保存在数据报里
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            //解析(读取)
            socket.receive(requestPacket);

            //获取上述数据报的数据，构成String
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //数据报（DatagramPacket）中getLength本身就是requestPacket.getData()的数据数

            //4、根据请求计算响应（回显)
            String response = this.process(request);

            //5、把响应写回客户端
            //将回显的String结果保存在数据报里
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), 0, response.getBytes().length,
                    requestPacket.getSocketAddress());
            //String的获取字节（response.getBytes()）数要response.getBytes().length
            socket.send(responsePacket);

            //请求的IP地址，端口号，请求，响应；
            System.out.printf("[%s,%d] req=%s, resp=%s\n",
                    requestPacket.getAddress(), requestPacket.getPort(), request, response);
            //日志多出的斜杠是InetAddress toString自带的，端口号是系统自动分配的
        }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}
